//
//  SetMeetingAccountViewController.m
//  YUNWUMeetingDemo
//
//  Created by mac on 2019/7/11.
//  Copyright © 2019 DGL. All rights reserved.
//

#import "SetMeetingAccountViewController.h"
#import "MeetingVideoViewController.h"
#import "MeetingHelper.h"
#import "AppDelegate.h"

@interface SetMeetingAccountViewController ()<UITextFieldDelegate,CloudroomVideoMgrCallBack>

@property (nonatomic,strong) UITextField *roomTextField;
@property (nonatomic,strong) UIButton *joinRoomBtn;
@property (nonatomic,strong) UIButton *creationRoomBtn;

@property (nonatomic, assign) BOOL createMeeting;
@property (nonatomic, copy) NSString *meetingID;

@end

@implementation SetMeetingAccountViewController
- (void)dealloc{
    self.roomTextField.delegate = nil;
    self.navigationController.delegate = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"加入房间/创建房间";
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self _commonSetup];//设置属性
    [self setUI];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self _updateDelegate];
}
#pragma mark - VideoMgrDelegate
// 登录成功
- (void)loginSuccess:(NSString *)usrID cookie:(NSString *)cookie {
    [HUDUtil hudHiddenProgress:YES];
    if (_createMeeting) {
        [self _handleCreateMeeting];
    } else {
        [self _handleEnterMeeting];
    }
}
// 登录失败
- (void)loginFail:(CRVIDEOSDK_ERR_DEF)sdkErr cookie:(NSString *)cookie {
    [HUDUtil hudHiddenProgress:YES];
    
    if (sdkErr == CRVIDEOSDK_NOSERVER_RSP) {
        [HUDUtil hudShow:@"服务器无响应" delay:3 animated:YES];
    }
    else if (sdkErr == CRVIDEOSDK_LOGINSTATE_ERROR) {
        [HUDUtil hudShow:@"登陆状态不对" delay:3 animated:YES];
        [[CloudroomVideoMgr shareInstance] logout];
    }
    else if (sdkErr == CRVIDEOSDK_SOCKETTIMEOUT) {
        [HUDUtil hudShow:@"网络超时" delay:3 animated:YES];
    }
    else {
        [HUDUtil hudShow:@"登录失败" delay:3 animated:YES];
    }
}
// 创建房间成功回调
- (void)createMeetingSuccess:(MeetInfo *)meetInfo cookie:(NSString *)cookie {
    [HUDUtil hudHiddenProgress:YES];
    [self _jumpToMeetingWithMeetInfo:meetInfo];
}

// 创建房间失败回调
- (void)createMeetingFail:(CRVIDEOSDK_ERR_DEF)sdkErr cookie:(NSString *)cookie {
    [HUDUtil hudHiddenProgress:YES];
    [HUDUtil hudShow:@"创建失败" delay:3 animated:YES];
}
#pragma mark - private method
- (void)_commonSetup {
    // 设置属性
    [self _setupProperty];
    // 设置代理
    [self _updateDelegate];
}
/* 设置属性 */
- (void)_setupProperty {
    _createMeeting = NO;
}
//创建
- (void)_loginAndCreateMeeting {
    _createMeeting = YES;
    [self _handleLogin];
}
//加入
- (void)_loginAndEnterMeeting:(NSString *)inputText {
    _createMeeting = NO;
    _meetingID = inputText;
    [self _handleLogin];
}
/* 更新代理 */
- (void)_updateDelegate {
//        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//        [appDelegate.videoMgrCallBack setVideoMgrDelegate:self];
    
    CloudroomVideoMgr *cloudroomVideoMgr = [CloudroomVideoMgr shareInstance];
    [cloudroomVideoMgr setMgrCallback:self];
}
/* 登录 */
- (void)_handleLogin {
    MeetingHelper *meetingHelper = [MeetingHelper shareInstance];
    [meetingHelper readInfo];
    
    NSString *nickname = meetingHelper.nickname;
    if ([NSString stringCheckEmptyOrNil:nickname]) {
        nickname = [NSString stringWithFormat:@"iOS_%04zd", [self _randomNumFrom:1000 to:9999]];
    }
    
    // 云屋SDK登陆账号,实际开发中,请联系云屋工作人员获取
    NSString *account = meetingHelper.account;
    // 密码通过MD5以后
    NSString *pswd = meetingHelper.pswd;
    // 服务器地址
    NSString *server = meetingHelper.server;
    
    if ([NSString stringCheckEmptyOrNil:server]) {
        [HUDUtil hudShow:@"服务器地址不能为空!" delay:3 animated:YES];
        return;
    }
    
    if ([NSString stringCheckEmptyOrNil:account]) {
        [HUDUtil hudShow:@"账号不能为空!" delay:3 animated:YES];
        return;
    }
    
    if ([NSString stringCheckEmptyOrNil:pswd]) {
        [HUDUtil hudShow:@"密码不能为空!" delay:3 animated:YES];
        return;
    }
    
    NSString *md5Pswd = [NSString md5:meetingHelper.pswd];
    
    MLog(@"server:%@ nickname:%@ account:%@ pswd:%@", server, nickname, account, md5Pswd);
    
    CloudroomVideoMgr *cloudroomVideoMgr = [CloudroomVideoMgr shareInstance];
    CloudroomVideoSDK *cloudroomVideoSDK = [CloudroomVideoSDK shareInstance];
    LoginDat *loginData = [[LoginDat alloc] init];
    [loginData setNickName:nickname];
    [loginData setAuthAcnt:account];
    [loginData setAuthPswd:md5Pswd];
    [loginData setPrivAcnt:nickname];
    
    [meetingHelper writeAccount:account pswd:pswd server:server];
    [meetingHelper writeNickname:nickname];
    
    // 设置服务器地址
    [cloudroomVideoSDK setServerAddr:server];
    
    [HUDUtil hudShowProgress:@"正在登录中..." animated:YES];
    
    // 开始上传日志
//    [[CloudroomVideoSDK shareInstance] startLogReport:nickname server:@"logserver.cloudroom.com:12005"];
    
    [self _updateDelegate];
    
    // 发送"登录"指令
    NSString *cookie = [NSString stringWithFormat:@"%f",CFAbsoluteTimeGetCurrent()];
    [cloudroomVideoMgr login:loginData cookie:cookie];
}
/* 创建房间 */
- (void)_handleCreateMeeting {
    NSString *userID = [[MeetingHelper shareInstance] nickname];
    NSString *title = nil;
    if (![NSString stringCheckEmptyOrNil:userID]) {
        title = [NSString stringWithFormat:@"%@的视频房间", userID];
    }
    
    [HUDUtil hudShowProgress:@"正在创建房间..." animated:YES];
    NSString *cookie = [NSString stringWithFormat:@"%f", CFAbsoluteTimeGetCurrent()];
    // 发送"创建房间"命令(不设置密码)
    [[CloudroomVideoMgr shareInstance] createMeeting:title createPswd:NO cookie:cookie];
}
/* 进入房间 */
- (void)_handleEnterMeeting {
    NSString *inputText = _meetingID;
    if ([NSString stringCheckEmptyOrNil:inputText]) {
        [HUDUtil hudShow:@"房间号不能为空" delay:3 animated:YES];
        return;
    }
    
    MeetInfo *meetInfo = [[MeetInfo alloc] init];
    [meetInfo setID:[inputText intValue]];
    [meetInfo setPswd:@""];
    
    [self _jumpToMeetingWithMeetInfo:meetInfo];
}
/**
 跳转到"房间"界面
 @param meetInfo 房间信息
 */
- (void)_jumpToMeetingWithMeetInfo:(MeetInfo *)meetInfo {
    MeetingVideoViewController *meetingVC = [[MeetingVideoViewController alloc]init];
    [meetingVC setMeetInfo:meetInfo];
    if (meetingVC) {
        [self presentViewController:meetingVC animated:YES completion:nil];
    }
}
/* 四位随机数生成 参考: [iOS 随机数生成][https://www.jianshu.com/p/f3f26608d1dd] */
- (NSInteger)_randomNumFrom:(NSInteger)from to:(NSInteger)to {
    return (from + (NSInteger)(arc4random() % (to - from + 1)));
}



#pragma mark -- Action
//加入房间
- (void)joinAction{
    [self _loginAndEnterMeeting:_roomTextField.text];
}
//创建房间
- (void)creationAction{
    [self _loginAndCreateMeeting];
}

#pragma mark -- UI
- (void)setUI{
    UILabel *textLabel = [[UILabel alloc]init];
    textLabel.text = @"请输入房间号";
    textLabel.font = [UIFont boldSystemFontOfSize:20];
    textLabel.textColor = [UIColor grayColor];
    [self.view addSubview:textLabel];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.top.mas_equalTo(self.view.mas_top).offset(30);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(30);
    }];
    
    _roomTextField = [[UITextField alloc]init];
    _roomTextField.placeholder = @"请输入房间号";
    _roomTextField.font = [UIFont systemFontOfSize:15];
    _roomTextField.borderStyle = UITextBorderStyleRoundedRect;
    _roomTextField.delegate = self;
    _roomTextField.textColor = [UIColor blackColor];
    _roomTextField.inputAccessoryView = [self addToolbar];
    _roomTextField.returnKeyType = UIReturnKeyDone;
    [self.view addSubview:_roomTextField];
    [_roomTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textLabel.mas_left);
        make.right.mas_equalTo(textLabel.mas_right);
        make.top.mas_equalTo(textLabel.mas_bottom).offset(15);
        make.height.mas_equalTo(50);
    }];
    
    _joinRoomBtn = [[UIButton alloc]init];
    [_joinRoomBtn setTitle:@"加入房间" forState:UIControlStateNormal];
    _joinRoomBtn.backgroundColor = [UIColor grayColor];
    _joinRoomBtn.layer.cornerRadius = 10;
    [_joinRoomBtn addTarget:self action:@selector(joinAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_joinRoomBtn];
    [_joinRoomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(_roomTextField);
        make.top.mas_equalTo(_roomTextField.mas_bottom).offset(15);
    }];
    
    UILabel *testLabel = [[UILabel alloc]init];
    testLabel.text = @"无房间号，可点击下方按钮创建房间";
    testLabel.font = [UIFont boldSystemFontOfSize:20];
    testLabel.textColor = [UIColor grayColor];
    [self.view addSubview:testLabel];
    [testLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.top.mas_equalTo(_joinRoomBtn.mas_bottom).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(20);
    }];
    
    _creationRoomBtn = [[UIButton alloc]init];
    [_creationRoomBtn setTitle:@"创建房间" forState:UIControlStateNormal];
    _creationRoomBtn.backgroundColor = [UIColor grayColor];
    _creationRoomBtn.layer.cornerRadius = 10;
    [_creationRoomBtn addTarget:self action:@selector(creationAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_creationRoomBtn];
    [_creationRoomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(_roomTextField);
        make.top.mas_equalTo(testLabel.mas_bottom).offset(15);
    }];
}

#pragma mark -- UITextFieldDelegate
#pragma mark -- 撤销键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
//键盘添加完成
- (UIToolbar *)addToolbar{
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 35)];
    toolbar.tintColor = [UIColor blueColor];
    toolbar.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(textFieldDone)];
    bar.tintColor = [UIColor grayColor];
    toolbar.items = @[space, bar];
    return toolbar;
}
- (void)textFieldDone{
    [self.view endEditing:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

@end
